package com.xjrsoft.module.customerTwo.EMP.dormitory_room.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.page.ConventPage;

import java.util.HashSet;
import java.util.List;
import com.xjrsoft.common.utils.DataTransUtil;
import com.xjrsoft.common.result.Response;
import com.xjrsoft.core.tool.utils.BeanUtil;
import com.xjrsoft.module.customerTwo.EMP.dormitory_room.dto.TDormitoryRoomDto;
import com.xjrsoft.module.customerTwo.EMP.dormitory_room.dto.SaveTDormitoryRoomFormDataDto;
import com.xjrsoft.module.customerTwo.EMP.dormitory_room.vo.TDormitoryRoomVo;
import com.xjrsoft.module.customerTwo.EMP.dormitory_room.vo.TDormitoryRoomListVo;
import com.xjrsoft.module.customerTwo.EMP.dormitory_room.dto.TDormitoryRoomListDto;
import com.xjrsoft.core.secure.utils.SecureUtil;
import com.xjrsoft.core.tool.utils.FlowableUtil;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.io.File;
import com.xjrsoft.core.tool.utils.CollectionUtil;
import com.xjrsoft.core.tool.utils.IoUtil;
import com.xjrsoft.module.excel.entity.XjrExcelImport;
import com.xjrsoft.module.excel.factory.ParserFactory;
import com.xjrsoft.module.excel.parser.ImportDataParser;
import com.xjrsoft.module.excel.service.IXjrExcelImportService;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;

import org.springframework.web.bind.annotation.*;
import com.xjrsoft.module.customerTwo.EMP.dormitory_room.entity.TDormitoryRoom;
import com.xjrsoft.module.customerTwo.EMP.dormitory_room.vo.TDormitoryRoomVo;
import com.xjrsoft.module.customerTwo.EMP.dormitory_room.service.ITDormitoryRoomService;

/**
 *  控制器
 *
 * @author dongxinhang
 * @since 2023-07-20
 */
@RestController
@AllArgsConstructor
@RequestMapping("/dormitory_room")
@Api(value = "宿舍房间管理", tags = "宿舍房间管理接口")
public class TDormitoryRoomController {

	private final IXjrExcelImportService importService;


	private final ITDormitoryRoomService tDormitoryRoomService;


	/**
	 * 详情 
	 */
	@GetMapping("/{id}")
	@ApiOperation(value = "详情", notes = "传入tDormitoryRoom")
	@SaCheckPermission(value = {"dormitory_room:view", "dormitory_room:modify"}, mode = SaMode.OR)
	public Response<TDormitoryRoomVo> getFormData(@PathVariable String id) {
		// 主表数据
		TDormitoryRoom tDormitoryRoom = tDormitoryRoomService.getById(id);
		tDormitoryRoom.setPart(tDormitoryRoom.getPart()+","+tDormitoryRoom.getFloor());
		TDormitoryRoomVo tDormitoryRoomVo = BeanUtil.copy(tDormitoryRoom, TDormitoryRoomVo.class);
		return Response.ok(tDormitoryRoomVo);
	}
	/**
	 * 自定义分页 
	 */
	@GetMapping
	@ApiOperation(value = "分页", notes = "传入tDormitoryRoom")
		public Response<PageOutput<TDormitoryRoomListVo>> getPageList(TDormitoryRoomListDto listDto) {
		IPage<TDormitoryRoom> page = tDormitoryRoomService.getPageList(listDto);
		page.getRecords().stream().forEach(e->e.setPart(e.getPart()+","+e.getFloor()));
		List<TDormitoryRoomListVo> records = BeanUtil.copyList(page.getRecords(), TDormitoryRoomListVo.class);
			// 转换列表数据
		DataTransUtil.transListShowData(records);
			// 工作流数据处理
		FlowableUtil.systemFormList(records, SecureUtil.getModuleId());
		return Response.ok(ConventPage.getPageOutput(page.getTotal(), records));
	}

	/**
	 * 新增 
	 */
	@PostMapping
	@ApiOperation(value = "新增", notes = "传入tDormitoryRoom")
	@SaCheckPermission("dormitory_room:add")
	public Response save(@RequestBody SaveTDormitoryRoomFormDataDto formDto) {
		TDormitoryRoomDto tDormitoryRoomDto = formDto.getTDormitoryRoomDto();
		//判断房号是否重复
		if(tDormitoryRoomService.roomNumberExist(tDormitoryRoomDto.getRoomNumber(),"")){
			return Response.notOk("房号重复，请重新输入！");
		}
		TDormitoryRoom tDormitoryRoom = BeanUtil.copy(tDormitoryRoomDto, TDormitoryRoom.class);
		//处理楼栋楼层数据
		String part = tDormitoryRoom.getPart();
		tDormitoryRoom.setPart(part.split(",")[0]);
		tDormitoryRoom.setFloor(part.split(",")[1]);
		String dataId = tDormitoryRoomService.addTDormitoryRoom(tDormitoryRoom);
		return dataId == null ? Response.notOk() : Response.ok(dataId);
	}

	/**
	 * 修改 
	 */
	@PutMapping("/{id}")
	@ApiOperation(value = "修改", notes = "传入tDormitoryRoom")
	@SaCheckPermission("dormitory_room:modify")
	public Response update(@PathVariable String id, @RequestBody SaveTDormitoryRoomFormDataDto formDto) {
		TDormitoryRoomDto tDormitoryRoomDto = formDto.getTDormitoryRoomDto();
		//判断房号是否重复
		if(tDormitoryRoomService.roomNumberExist(tDormitoryRoomDto.getRoomNumber(),id)){
			return Response.notOk("房号重复，请重新输入！");
		}
		TDormitoryRoom tDormitoryRoom = BeanUtil.copy(tDormitoryRoomDto, TDormitoryRoom.class);
		//处理楼栋楼层数据
		String part = tDormitoryRoom.getPart();
		tDormitoryRoom.setPart(part.split(",")[0]);
		tDormitoryRoom.setFloor(part.split(",")[1]);
		return Response.status(tDormitoryRoomService.updateTDormitoryRoom(id, tDormitoryRoom));
	}



	/**
	 * 删除 
	 */
	@DeleteMapping("/{ids}")
	@ApiOperation(value = "删除", notes = "传入ids")
	@SaCheckPermission(value = {"dormitory_room:batchDelete", "dormitory_room:delete"}, mode = SaMode.OR)
	public Response remove(@ApiParam(value = "主键集合", required = true) @PathVariable String ids) {
		return Response.status(tDormitoryRoomService.delete(ids));
	}


	/**
	 * excel批量导入数据
	 */
	@PostMapping("/import")
	@ApiOperation(value = "excel批量导入数据", notes = "传入菜单id")
	@SaCheckPermission("dormitory_room:import")
	public Response importData(@RequestParam("F_ModuleId") String moduleId, MultipartFile file) {
		XjrExcelImport excelImport = importService.getByModuleId(moduleId);
		ImportDataParser parser = ParserFactory.getImportDataParser();
		File excelFile = IoUtil.toFile(file);
		List<Map<String, Object>> recordList = parser.parseDataToMap(excelImport, excelFile);
		if (CollectionUtil.isNotEmpty(recordList)) {
			List<TDormitoryRoom> entities = recordList.stream().map(record ->
				BeanUtil.toDtoBean(record, TDormitoryRoom.class)
			).collect(Collectors.toList());
			//处理床位数、楼层等字段
			Map<String,Map<String,String>> floorData = tDormitoryRoomService.getFloorData();
			Set<String> roomNumberSet = new HashSet<>();
			Set<String> notOnlyNumber = new HashSet<>();
			entities.stream().forEach(e->{
				if ("3".equals(e.getRoomType())||"4".equals(e.getRoomType())) {
					e.setBedNumber(2);
				}else {
					e.setBedNumber(1);
				}
				Map<String,String> floorMap = floorData.get(e.getPart());
				e.setFloor(floorMap.get(e.getFloor()));
				e.setUsedBedNumber(0);
				if(!roomNumberSet.add(e.getRoomNumber())){
					notOnlyNumber.add(e.getRoomNumber());
				}
			});
			//判断房号是否唯一
			if(CollectionUtil.isNotEmpty(notOnlyNumber)){
				return Response.notOk("房间号"+notOnlyNumber.toString()+"有重复，请检查！");
			}else{	//查询数据库看是否有重复
				List<String> list = tDormitoryRoomService.getRoomNumberList(roomNumberSet);
				if(CollectionUtil.isNotEmpty(list)){
					return Response.notOk("房间号"+list.toString()+"已存在，请检查！");
				}
			}
			return Response.status(tDormitoryRoomService.saveBatch(entities));
		}
		return Response.notOk();
	}
}
